var selectedRow = 1;
var options="";
var personsListOptions="";
function deleteChildren(parentId,childId){
	return $.ajax({
		type:"POST",
		async:false,
		url:'/elim/rest/persons/'+parentId+'/children/delete/' + childId,
		success:function(data){
			console.log(data);
			return true;
		},
		error:function(error,status, errorThrown){
			showError(error);
			return false;
		}});
}

function updateForm(){
	var text = $('.row_selected').children(":first").html();
	selectedRow = $('.row_selected .row-count').html();
	if(text != null)
		updateParishioner(text);
	$('#parishioner-update-form input').removeAttr("placeholder");
}

function updateChildren(id){
	$.get('/elim/rest/persons/'+id+'/children',
			function(children){
		$('.children-list').html(getChildrenList(id, children));
	});
}

function updateParishioner(id){
	$.get('/elim/rest/parishioners/update-form/'+id,
			function(data){
		if(data!=null){
			$("#parishioner-update-form").html(data);
			createDatePickers();
			// set options list for baptist
			$('.persons-names-option').html(options);
			$('#persons-list').html(options);
			// select the baptist from the list
			$('#'+id).attr('selected','selected');
			updateChildren(id);
			updatePhoto($('#parishioner-id').val());
		}
	});
}

function updateTableItem() {
	table = $('#parishioner-data-update').dataTable();
	table.fnUpdate($('#firstName').val(), selectedRow-1, 2);
	table.fnUpdate($('#lastName').val(), selectedRow-1, 3);
	table.fnDraw();
}

function addTableItem() {
	table = $('#parishioner-data-update').dataTable();
	var index = table.fnGetData().length + 1;
	table.fnAddData( [index,
	                  $('#firstName').val(),
	                  $('#lastName').val(),
	                  '']);

	table.fnDraw();
}

function getPersonsNamesOption(persons){
	var options="";
	var option = "<option id=\"{0}\" value=\"{0}\">{1}</option>"
		for (var index=0 ; index<persons.length ; index++ ){
			options += $.validator.format(option,persons[index][0],persons[index][2] + ' ' + persons[index][1]);
		}
	return options;
}

function getPersonsListOptions(persons){
	var options="";
	var option = "<option id=\"{0}\" value=\"{1}\"></option>"
		for (var index=0 ; index<persons.length ; index++ ){
			options += $.validator.format(option,persons[index][0],persons[index][2] + ' ' + persons[index][1]);
		}
	return options;
}

function getChildrenList(idParent,children){
	var items="";
	var item = "<li>" +
				"<div id=\"child\">" +
					"<a class=\"child-name\" id=\"{0}\" href=\"\">{1}</a>" +
				"</div>" +
				"<a class=\"remove-child-button small-edit-button\" id=\"{0}\">x</a>" +
			"</li>"
	// var item = "<li id=\"child{0}\" href=\"\">{1}</li>"
		if(children != null){
			for (var index=0 ; index<children.length ; index++ ){
				items += $.validator.format(item,children[index].idPerson, children[index].firstName + ' ' + children[index].lastName);
			}
		}
	return items;
}

require(["dataTables"], function() {
	$(document).ready(function() {
		var location = window.location.href;
		$(window).load(function() {
			updatePhoto($('#parishioner-id').val());
		});
		var text = location.slice(location.lastIndexOf('/')+1, location.indexOf("?"));
		$.get('/elim/rest/persons/names', function(persons){
			options=getPersonsNamesOption(persons);
			// personsListOptions = getPersonsListOptions(persons);
		});



		if ($('#person-id').html() != text)
			updateParishioner(text);

		$('#parishioner-data-update').dataTable({
			"iDisplayLength": 10
		});
		$('.parishioner-data tr').live("click",function(e) {
			unselectAllRows(this, e);
			selectRow(this, e);
			updateForm();
		});

		$("#update-button").live("click", function(event) {
			$.post('/elim/rest/parishioners/update',
					$('form').serialize(),
					function(data){
				showResult(data);
				if (data.success == true) {
					uploadPhoto(data.id);
					updateTableItem();
				}
			}
			).error(function(error,status,errorThrown){
				handleError(error,status,errorThrown);
			});
		});			    		

		$("#create-button").live("click", function(event) {
			// $.get('/elim/parishioners/create');
			$.post('/elim/rest/parishioners/create',
					$('form :input[id!="id"][id!="parishioner-id"]').serialize(),
					function(data){ 
				showResult(data);
				if (data.success == true) {
					if ($('#photo').val() == '')
						showDefaultPhoto();
					uploadPhoto(data.id);
					addTableItem();
				}
			}
			).error(function(error,status,errorThrown){
				handleError(error,status,errorThrown);
			});
		});

		$("#cancel-button").live("click", function(event) {
			if (confirm(jQuery.i18n.prop('ui.parishioners.confirm_quit')))
				listParishioners();
		});

		$("#person-fields input,textarea,select").live("change", function(event) {
			removeErrorClass(event);
			removeResultDiv();
		});

		$('#parishioner-update-form').live('keydown', 'Ctrl+s',function(event){
			$.post('/elim/rest/parishioners/update',
					$('form').serialize(),
					function(data){
				showResult(data);
			}
			).error(function(error,status,errorThrown){
				handleError(error,status,errorThrown);
			});
		});

		$('#photo').live('change', function(event) {
			previewPhoto(this);
		});
		$("#add-child-button").live("click", function(event) {
			var childId = $('#persons-list option:selected').attr('id');
			// console.log("Child to be added:" + childId);
			var parentId = $('#parishioner-id').val();
			$.ajax({
				type: "POST",
				url: '/elim/rest/persons/'+parentId+'/children',
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				data: ""+childId+"",
				success: function(children){
					var message = "Added "+children.child.idPerson+" to the parent " + children.parent.idPerson+"!"; 
					console.log(message);
					updateChildren(parentId);
					showResult(message);
				},
				error: function(error,status,errorThrown){
					showError(error);
				}
			});
		});
		
		$(".remove-child-button").live("click", function(event) {
			var childId = $(this).attr('id');
			// console.log("Child to be added:" + childId);
			var parentId = $('#parishioner-id').val();
			$.ajax({
				type: "POST",
				url: '/elim/rest/persons/'+parentId+'/children/delete',
				contentType: "application/json; charset=utf-8",
				data: ""+childId+"",
				success: function(message){
					console.log(message);
					updateChildren(parentId);
					showResult(message);
				},
				error: function(error,status,errorThrown){
					showError(error);
				}
			});
		});
		
		$('#parishioner-update-form').bind('keydown', 'Ctrl+down',function(event){
			selectNextRow();
			updateForm();
		});

		$('#parishioner-update-form').bind('keydown', 'Ctrl+up',function(event){
			selectPreviousRow();
			updateForm();
		});
	});
	/*CTRL + down arrow*/
	$.ctrlKey(40, function() {
		selectNextRow();
		updateForm();
	}, []);
	/*CTRL + down arrow*/
	$.ctrlKey(38, function() {
		selectPreviousRow();
		updateForm();
	}, []);
});
